# 在文件顶部添加系统路径
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import streamlit as st
import time
import shutil
from pathlib import Path
import tempfile
import pandas as pd
from service.video_processor import VideoProcessor
from service.ui_processor import UIProcessor  # 新增服务层处理类
from external.oss_utils import OssManager
from external.aliyun_asr import AliyunASR

# 自定义输出重定向类，用于捕获处理过程中的输出并显示在界面上
class StreamlitLogger:
    def __init__(self, log_placeholder):
        self.log_placeholder = log_placeholder
        self.log_text = ""

    def write(self, text):
        self.log_text += text
        self.log_placeholder.text_area("处理日志", self.log_text, height=300)

    def flush(self):
        pass

# 初始化OSS管理器
oss_manager = OssManager()

# 设置页面标题
st.set_page_config(page_title="视频处理工具", layout="wide")

# 标题和说明
st.title("视频处理工具")
st.markdown("""
这个工具可以帮助您：
1. 从视频中提取音频
2. 将音频转换为带时间戳的字幕
3. 根据字幕时间戳从视频中提取帧
4. 自动将文件保存到本地
""")

# 创建项目根目录下的output文件夹
project_root = Path(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
output_dir = project_root / "output"
os.makedirs(output_dir, exist_ok=True)

# 创建临时目录用于存储上传的视频
temp_dir = tempfile.mkdtemp()

# 注册清理函数
def cleanup():
    try:
        shutil.rmtree(temp_dir)
    except:
        pass

import atexit
atexit.register(cleanup)


# 创建UI处理器实例
ui_processor = UIProcessor(project_root, output_dir)

# 创建界面占位符
progress_placeholder = st.empty()
status_placeholder = st.empty()
log_placeholder = st.empty()
result_placeholder = st.empty()

# 在侧边栏 - 参数设置和功能选择部分
with st.sidebar:
    st.header("功能选择")
    
    # 添加功能选择选项
    function_mode = st.radio(
        "选择功能模式",
        ["视频自动处理", "视频+字幕处理", "单词数据集生成"]
    )
    
    st.header("参数设置")
    
    # 添加OSS设置选项 - 这部分保留并设为必选
    use_oss = st.checkbox("使用阿里云OSS存储", value=True, disabled=True)
    if not oss_manager.available:
        st.error("阿里云OSS访问凭证未设置，请配置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET")
        st.info("使用阿里云听悟API必须启用OSS存储")

# 主处理逻辑 - 根据选择的功能模式显示不同的界面
if function_mode == "视频自动处理":
    # 视频自动处理模式
    uploaded_file = st.file_uploader("上传视频文件", type=["mp4", "avi", "mov", "mkv"], accept_multiple_files=False, key="video_auto")
    
    # 获取IP数据集选项
    ip_options = ui_processor.get_ip_options(output_dir)
    # selected_ip = st.selectbox("选择已有IP数据集（选择none创建新的IP数据集）", ip_options)
    
    if uploaded_file:
        # 显示上传的文件
        st.write(f"已上传文件: {uploaded_file.name}")
        
        # 添加处理按钮
        if st.button("开始处理"):
            # 检查OSS是否可用
            if not oss_manager.available:
                st.error("阿里云OSS服务不可用，请检查凭证设置")
            else:
                # 保存上传的文件到临时目录
                video_path = os.path.join(temp_dir, uploaded_file.name)
                
                # 保存文件
                with open(video_path, "wb") as f:
                    f.write(uploaded_file.getbuffer())
                
                # 创建输出目录
                video_output_dir = os.path.join(output_dir, "videos", uploaded_file.name.split('.')[0])
                
                # 创建日志记录器
                logger = StreamlitLogger(log_placeholder)
                
                # 处理视频
                ui_processor.process_video(
                    video_path, 
                    video_output_dir, 
                    logger,
                    progress_placeholder,
                    status_placeholder,
                    result_placeholder
                )

elif function_mode == "视频+字幕处理":
    # 视频+字幕处理模式
    col1, col2 = st.columns(2)
    
    with col1:
        uploaded_video = st.file_uploader("上传视频文件", type=["mp4", "avi", "mov", "mkv"], accept_multiple_files=False, key="video_subtitle")
    
    with col2:
        uploaded_subtitle = st.file_uploader("上传字幕文件", type=["srt", "vtt", "ass", "lrc"], key="subtitle")
    
    # 获取IP元数据和显示选项
    ip_display_names, ip_options = ui_processor.get_ip_metadata_options(project_root, include_empty=True)
    ip_display_names.insert(0, "创建新的IP数据集")
    default_index = 0
    selected_display = st.selectbox("选择IP动画数据",
                                    ip_display_names if ip_display_names else ["无可用IP数据"],
                                    index=default_index)
    
    # 获取选择的IP ID
    selected_ip = ui_processor.get_selected_ip_id(ip_options, selected_display)
    
    if uploaded_video and uploaded_subtitle:
        # 显示上传的文件
        st.write(f"已上传视频文件: {uploaded_video.name}")
        st.write(f"已上传字幕文件: {uploaded_subtitle.name}")
        
        # 添加处理按钮
        if st.button("开始处理"):
            # 保存上传的文件到临时目录
            video_path = os.path.join(temp_dir, uploaded_video.name)
            subtitle_path = os.path.join(temp_dir, uploaded_subtitle.name)
            
            # 保存文件
            with open(video_path, "wb") as f:
                f.write(uploaded_video.getbuffer())
                
            with open(subtitle_path, "wb") as f:
                f.write(uploaded_subtitle.getbuffer())
            
            # 创建日志记录器
            logger = StreamlitLogger(log_placeholder)
            
            # 处理视频和字幕
            ui_processor.process_video_with_subtitle(
                video_path, 
                subtitle_path, 
                selected_ip,
                logger,
                progress_placeholder,
                status_placeholder,
                result_placeholder,
            )

elif function_mode == "单词数据集生成":
    # 单词数据集生成模式
    col1, col2 = st.columns(2)
    
    with col1:
        uploaded_word_list = st.file_uploader("上传单词列表文件", type=["txt"], key="word_list")
    
    with col2:
        # 获取IP元数据和显示选项
        ip_display_names, ip_options = ui_processor.get_ip_metadata_options(project_root, include_empty=True)
        default_index = 0
        selected_display = st.selectbox("选择IP动画数据",
                                        ip_display_names if ip_display_names else ["无可用IP数据"],
                                        index=default_index)
        # 获取选择的IP ID
        selected_ip = ui_processor.get_selected_ip_id(ip_options, selected_display)

    
    if uploaded_word_list and selected_ip != "none":
        # 显示上传的文件和选择的IP
        st.write(f"已上传单词列表文件: {uploaded_word_list.name}")
        st.write(f"已选择IP动画数据: {selected_display}")
        
        # 添加处理按钮
        if st.button("开始生成数据集"):
            # 保存上传的文件到临时目录
            word_list_path = os.path.join(temp_dir, uploaded_word_list.name)
            
            # 保存文件
            with open(word_list_path, "wb") as f:
                f.write(uploaded_word_list.getbuffer())
            
            # 创建日志记录器
            logger = StreamlitLogger(log_placeholder)
            
            # 生成单词数据集
            ui_processor.generate_word_dataset(
                word_list_path,
                selected_ip,
                logger,
                status_placeholder,
                result_placeholder
            )

    elif selected_ip == "none":
        st.warning("请先创建IP动画数据")